package jwt.duplo.game.core {
	import flash.display.DisplayObject;
	import flash.display.Loader;
	import flash.display.MovieClip;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.net.URLRequest;
	import flash.system.ApplicationDomain;
	import flash.system.LoaderContext;
	
	import org.osflash.signals.Signal;

	public class GameAssetProxy {
		
		public var complete:Signal;
		public var progress:Signal;
		public var error:Signal;
		private var _loader:Loader;
		public var request:URLRequest;
		
		private static const _instance:GameAssetProxy = new GameAssetProxy();
		public static function get instance():GameAssetProxy { return _instance; }
		
		public function GameAssetProxy() {
			if(_instance) throw new Error("GameAssetProxy is singleton, use .instance instead.");
		 	complete = new Signal();
			progress = new Signal(Number);
			error = new Signal(String);
			request = new URLRequest();
			_loader = new Loader();
			_loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onComplete);
			_loader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, onProgress);
			_loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, onError);
		}
		
		public function send(url:String="Assets.swf"):void {
			request.url = url;
			_loader.load(request, new LoaderContext(false, ApplicationDomain.currentDomain));
		}
		
		private function onProgress(e:ProgressEvent):void {
			progress.dispatch(e.bytesLoaded / e.bytesTotal);
		}
		
		private function onError(e:IOErrorEvent):void {
			error.dispatch(e.text);
		}
		
		private function onComplete(e:Event):void {
			complete.dispatch();
			complete.removeAll();
			progress.removeAll();
			error.removeAll();
		}
		
		public function get data():DisplayObject {
			return _loader.content;
		}
	}
}